package com.shangdiao.sd_server.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shangdiao.sd_server.constant.Constant;
import com.shangdiao.sd_server.constant.ErrorCode;
import com.shangdiao.sd_server.pojo.ResponseMsg;
import com.shangdiao.sd_server.service.RedisService;
import com.shangdiao.sd_server.util.FastjsonUtil;
import com.shangdiao.sd_server.util.RequestRenderUtil;
import com.shangdiao.sd_server.util.SpringUtil;
import com.shangdiao.sd_server.util.StringUtil;

/**
 * 通行证验证过滤器
 * 
 * @author btshen
 */
public class ServerValidateFilter implements javax.servlet.Filter {

	protected Logger log = LoggerFactory.getLogger(getClass());

	private RedisService redisService;

	public void init(FilterConfig filterConfig) throws ServletException {
		redisService = SpringUtil.getBean(RedisService.class);
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

		ResponseMsg retMsg = null;

		HttpServletResponse rs = (HttpServletResponse) response;
		String token_in = redisService.get(Constant.SERVER_TOKEN_PRE);
		
		if (!StringUtil.isBlank(token_in)) {
			redisService.set(Constant.SERVER_TOKEN_PRE, token_in, 60 * 100);
			chain.doFilter(request, response);
		} else {
			retMsg = new ResponseMsg("登录验证失败！", ErrorCode.INVALID_SID, null);
			RequestRenderUtil.renderText(rs, FastjsonUtil.toJSONString(retMsg),
					"utf-8");
			return;
		}
		
//		chain.doFilter(request, response);
	}

	public void destroy() {

	}
}
